<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>文件列表</title>
  </head>
  <body>
    <h1>
      <button><a href="/" target="_self">文件上传-可以拖拽</a></button>
      文件列表
    </h1>
    <ul id="file-list"></ul>

    <script>
      function getFileList() {
        fetch("http://localhost:8001/filelist")
          .then((response) => response.json())
          .then((data) => {
            if (data.code === 200) {
              const fileList = data.data.files;
              const ul = document.getElementById("file-list");

              fileList.forEach((file) => {
                const li = document.createElement("li");
                const link = document.createElement("a");
                link.textContent = file;

                link.href = `http://localhost:8001/download/${file}`;
                link.download = file;
                li.appendChild(link);

                const deleteBtn = document.createElement("button");
                deleteBtn.textContent = "删除";
                deleteBtn.addEventListener("click", () => deleteFile(file));
                li.appendChild(deleteBtn);

                ul.appendChild(li);
              });
            } else {
              console.error("Error retrieving file list:", data.message);
            }
          })
          .catch((error) => {
            console.error("Error retrieving file list:", error);
          });
      }

      function downloadFile(fileName) {
        fetch(`http://localhost:8001/download/${fileName}`)
          .then((response) => response.blob())
          .then((blob) => {
            const link = document.createElement("a");
            link.href = URL.createObjectURL(blob);
            link.download = fileName;
            link.click();
          })
          .catch((error) => {
            console.error("Error downloading file:", error);
          });
      }

      function deleteFile(fileName) {
        fetch(`http://localhost:8001/delete/${fileName}`, { method: "DELETE" })
          .then((response) => response.json())
          .then((data) => {
            if (data.code === 200) {
              // 文件删除成功，重新加载文件列表
              window.location.reload();
            } else {
              console.error("Error deleting file:", data.message);
            }
          })
          .catch((error) => {
            console.error("Error deleting file:", error);
          });
      }

      // 调用 getFileList 来加载文件列表
      getFileList();
    </script>
  </body>
</html>
